//
//  77ClubTabBarViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import UIKit
import Lottie

class ClubTabBarViewController: UITabBarController {

    let pages: [UIViewController] = [ClubHomeViewController(), ClubInfoViewController(), ClubSquareViewController(), ClubMineViewController()]
    let imageName: [String] = ["home", "info", "square", "mine"]
    let titleName: [String] = ["游戏", "资讯", "广场", "我的" ]
//    private var animationView: LottieAnimationView?
//    private let lottieNameArr: [String] = ["home", "info", "square", "mine"]
//    private lazy var tabBarSwappableImageViews: [UIImageView] = {
//        //        2.遍历取出所有的 tabBarButton
//        var tempArray = [UIImageView]()
//        for tempView in self.tabBar.subviews where tempView.isKind(of: NSClassFromString("UITabBarButton")!) {
//
//            for tempImgV in tempView.subviews {
//                //2.1 继续遍历tabBarButton 找到 UITabBarSwappableImageView 并保存
//                //第一种层级关系 UITabBarButton --> UITabBarSwappableImageView
//                if tempImgV.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) {
//
//                    tempArray.append(tempImgV as! UIImageView)
//                }
//            }
//        }
//        return tempArray
//    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.delegate = self
        self.tabBar.backgroundImage = UIImage()
        self.tabBar.backgroundColor = "#F7F8FA".toColor
        
        for i in 0..<pages.count {
            configPages(page: pages[i], name: imageName[i], tag: i)
        }
        setValue(ClubTabBar(), forKey: "tabBar")
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateUserInfo), name: .reloadWebView, object: nil)
    }
    
    private func configPages(page: UIViewController, name: String, tag: Int) {
        page.tabBarItem.title = titleName[tag]
        page.tabBarItem.image = "Tab_\(name)_nor".toImage?.withRenderingMode(.alwaysOriginal)
        page.tabBarItem.selectedImage = "Tab_\(name)_sel".toImage?.withRenderingMode(.alwaysOriginal)

        let tabBarAppearance = UITabBarAppearance()
        tabBarAppearance.shadowColor = .clear
        tabBarAppearance.backgroundEffect = nil
        page.tabBarItem.standardAppearance = tabBarAppearance
        if #available (iOS 15, *) {
            page.tabBarItem.scrollEdgeAppearance = tabBarAppearance
        }
        let nav = ClubNavViewController(rootViewController: page)
        nav.tabBarItem.tag = tag
        addChild(nav)
    }
    
    @objc private func updateUserInfo (){        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task {
                let res = await network.request(.mineInfo(uid: uid),type: ClubMineModel.self)
                if res.isSuccess, let model = res.model {
                    ClubUser = model.user
                }
            }
        }
    }
}

//MARK: 动画
extension ClubTabBarViewController: UITabBarControllerDelegate {
    
    func selectedTabController(index: Int){
        selectedIndex = index
        guard let vc = self.viewControllers?[index] else { return }
//        setupAnimation(self, vc)
    }
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
//        setupAnimation(tabBarController, viewController)
    }
    
    // 隐藏所有选项卡的文字
    func hideTabBarItemsText() {
        
        if selectedIndex == 0 {
            tabBar.selectedItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .normal)
        }
    }
    
//    private func getAnimationViewAtTabBarIndex(_ index: Int, _ frame: CGRect)-> LottieAnimationView{
//        
//        let view = LottieAnimationView(name: lottieNameArr[index])
//        view.frame = frame
//        view.contentMode = .scaleAspectFill
//        view.animationSpeed = 1
//        return view
//    }
//
//    private func setupAnimation(_ tabBarVC: UITabBarController, _ viewController: UIViewController){
//
//        if animationView != nil {
//            animationView!.stop()
//            animationView?.removeFromSuperview()
//        }
//
//    //        1. 获取当前点击的是第几个
//        let index = tabBarVC.viewControllers?.firstIndex(of: viewController)
////        3. 找到当前的UITabBarButton
//        let currentTabBarSwappableImageView = tabBarSwappableImageViews[index!]
//
////        4. 获取UITabBarButton中的 UITabBarSwappableImageView 并隐藏
//        var frame = currentTabBarSwappableImageView.frame
//        frame.origin.x = 0
//        frame.origin.y = 0
//        frame.size.width = 36
//        frame.size.height = 36
//        let animation: LottieAnimationView? = getAnimationViewAtTabBarIndex(index!, frame)
//        self.animationView = animation
//         self.animationView!.center = currentTabBarSwappableImageView.center
//    //        5. 创建动画 view 加载到 当前的 UITabBarButton 并隐藏 UITabBarSwappableImageView
//        currentTabBarSwappableImageView.superview?.addSubview( animation!)
//        currentTabBarSwappableImageView.isHidden = true
//        animation?.play(fromProgress: 0, toProgress: 0.8, loopMode: .playOnce) { finish in
//            currentTabBarSwappableImageView.isHidden = false
//        }        
//    }
}

class ClubTabBar: UITabBar {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundImage = UIImage()
        shadowImage = nil
        barTintColor = .clear
        self.backgroundColor = "#F7F8FA".toColor
        
        UITabBar.appearance().tintColor = "#000000".toColor
        UITabBar.appearance().unselectedItemTintColor = "#47494D".toColor
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
